from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'code', 'unit', 'purchase_price', 'sale_price', 
                 'stock', 'warning_stock', 'status', 'create_time', 'update_time']
        read_only_fields = ['id', 'create_time', 'update_time']

    def validate_code(self, value):
        if self.instance and self.instance.code == value:
            return value
        if Product.objects.filter(code=value).exists():
            raise serializers.ValidationError('商品编码已存在')
        return value

    def validate_purchase_price(self, value):
        if value <= 0:
            raise serializers.ValidationError('采购价必须大于0')
        return value

    def validate_sale_price(self, value):
        if value <= 0:
            raise serializers.ValidationError('销售价必须大于0')
        return value

    def validate_stock(self, value):
        if value < 0:
            raise serializers.ValidationError('库存不能小于0')
        return value

    def validate_warning_stock(self, value):
        if value < 0:
            raise serializers.ValidationError('预警库存不能小于0')
        return value 